/*
 * connection_manager.cpp
 *
 *  Created on: 2021年2月2日
 *      Author: kimfeng
 */

#include "connection_manager.h"
#include <boost/bind/bind.hpp>

connection_manager::connection_manager(boost::asio::io_service& io_svc) :
	m_timer(io_svc), m_last_id(0)
{
	m_timer.expires_from_now(boost::posix_time::seconds(3));
	m_timer.async_wait(boost::bind(&connection_manager::handle_timeout, this));
}

connection_manager::~connection_manager()
{
}

void connection_manager::start(connection_ptr c)
{
	m_mutex.lock();
	uint64_t id = get_connection_id();
	m_connections[id] = c;
	c->start(id);
	m_mutex.unlock();
}

void connection_manager::stop(connection_ptr c)
{
	m_mutex.lock();
	m_connections.erase(c->get_id());
	m_mutex.unlock();
	c->stop();
}

void connection_manager::send_heartbeat()
{
}

void connection_manager::check_alive()
{
	m_mutex.lock();
	log_debug("%llu connections", m_connections.size());
	std::map<connection_id_t, connection_ptr>::iterator itr = m_connections.begin();
	while (itr != m_connections.end())
	{
		++itr;
	}
	m_mutex.unlock();
}

void connection_manager::handle_timeout()
{
	check_alive();
	m_timer.expires_from_now(boost::posix_time::seconds(3));
	m_timer.async_wait(boost::bind(&connection_manager::handle_timeout, this));
}

connection_id_t connection_manager::get_connection_id()
{
	if (++m_last_id == 0) m_last_id = 1;
	return m_last_id;
}

connection_ptr connection_manager::get_connection(connection_id_t id)
{
	connection_ptr c = NULL;

	m_mutex.lock();
	std::map<connection_id_t, connection_ptr>::iterator itr =
			m_connections.find(id);
	if (itr != m_connections.end())
	{
		c = itr->second;
	}
	m_mutex.unlock();

	return c;
}
